import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ImageToOledRow {

    private static int max_width = 128;
    private static int max_height = 64;
    private static int CHAR_SIZE = 8;

    public static void main(String[] args) {
        try {
            imgToHex("/Users/casually/Library/Mobile Documents/com~apple~CloudDocs/ps/mkllogo.bmp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void imgToHex(String path) throws IOException {
        BufferedImage image = ImageIO.read(new File(path));
        int w = image.getWidth();
        int h = image.getHeight();

        w = w < max_width ? w : max_width;
        h = h < max_height ? h : max_height;

        float[] rgb = new float[3];
        float red = 0;
        float green = 0;
        float blue = 0;

        double SW = 175;


        int widthNumber = w % CHAR_SIZE != 0 ? (w / CHAR_SIZE + 1) : w / 8;

        for (int y = 0; y < h; y++) {
            StringBuffer sb = new StringBuffer();
            sb.append("{");
            for (int i = 0; i < widthNumber; i++) {
                int x_max = i * CHAR_SIZE;
                String str = "";
                for (int x = x_max; x < x_max + CHAR_SIZE; x++) {
                    if (x > w) {
                        str += "0";
                        continue;
                    }
                    int pixel = image.getRGB(x, y);
                    rgb[0] = (pixel & 0xff0000) >> 16;
                    rgb[1] = (pixel & 0xff00) >> 8;
                    rgb[2] = (pixel & 0xff);
                    red += rgb[0];
                    green += rgb[1];
                    blue += rgb[2];
                    float avg = (rgb[0] + rgb[1] + rgb[2]) / 3;
                    if (avg <= SW) {
                        str = "0" + str;
                    } else {
                        str = "1" + str;
                    }
                }
                sb.append(parseByte2HexStr(str));
                sb.append(",");
            }
            sb.append("},");
            System.out.println(sb.toString());
        }
    }

    /**
     * @param str
     * @return
     * @description 将二进制转换成16进制
     */
    public static String parseByte2HexStr(String str) {
        String hex = Integer.toHexString(Integer.parseInt(str, 2));
        return "0x" + (hex.length() == 1 ? "0" + hex : hex).toUpperCase();
    }
}

